package com.tywj.buscustomerapp.service;

import android.app.DownloadManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.webkit.MimeTypeMap;


import com.tywj.buscustomerapp.App;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.utils.SdcardUtils;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.umeng.commonsdk.statistics.common.MLog;

import java.io.File;

import okhttp3.ResponseBody;


/**
 * Created by dcqia on 2017/12/20.
 */

public class UpdateService extends Service {
        private String apkURL;

        private NotificationManager notificationManager;

        private NotificationCompat.Builder builder;

        private int mProceess = -1;

        private static final String PACKAGE_NAME = App.getContext().getPackageName();

        private static final String APP_NAME = "胖哒";
        private DownloadManager downloadManager;
        private long mTaskId;

        @Override
        public void onDestroy() {
            super.onDestroy();
            unregisterReceiver(receiver);
        }

        @Override
        public void onCreate() {
            notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            if (intent == null) {
                notifyUser("下载失败", 0);
//                stopSelf();//取消
            } else {
                apkURL = intent.getStringExtra("apkUrl");
                initNotify();
                initFileDir();
                if (apkURL!=null && !apkURL.equals("")){
                    notifyUser("下载开始", 0);
                    File apkFile = new File("/mnt/sdcard/com.tywj.buscustomerapp/胖哒.apk");
                    if (apkFile.exists()){
                        apkFile.delete();
                    }
                    downloadAPK(apkURL);//启动下载
                }else{
                    notifyUser("下载失败", 0);
                    stopSelf();//取消
                }
            }
            return super.onStartCommand(intent, flags, startId);
        }

        /**
         * 创建文件夹
         */
        private void initFileDir() {
        }

        private void initNotify() {
            builder = new NotificationCompat.Builder(this);
            builder.setContentTitle(APP_NAME);
            builder.setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
            builder.setAutoCancel(true);
            builder.setWhen(System.currentTimeMillis());
            builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(),
                    PendingIntent.FLAG_UPDATE_CURRENT));
        }

    //使用系统下载器下载
    private void downloadAPK(String versionUrl) {
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
        request.setAllowedOverRoaming(true);//漫游网络是否可以下载

        //设置文件类型，可以在下载结束后自动打开该文件
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));
        request.setMimeType(mimeString);

        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);

        //sdcard的目录下的download文件夹，必须设置
//        request.setDestinationInExternalPublicDir("/mnt/sdcard/com.voga.readcool/", "胖哒.apk");
        request.setDestinationInExternalFilesDir(this,"","胖哒.apk");
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        mTaskId = downloadManager.enqueue(request);
        //注册广播接收者，监听下载状态
        registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkDownloadStatus();//检查下载状态
        }
    };

    private void checkDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(mTaskId);//筛选下载任务，传入任务ID，可变参数
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    MLog.i(">>>下载暂停");
                case DownloadManager.STATUS_PENDING:
                    MLog.i(">>>下载延迟");
                case DownloadManager.STATUS_RUNNING:
                    MLog.i(">>>正在下载");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    MLog.i(">>>下载完成");
                    installAPK();

                    break;
                case DownloadManager.STATUS_FAILED:
                    MLog.i(">>>下载失败");
                    ToastUtils.show("下载失败");
                    UpdateService.this.stopSelf();
                    break;
            }
        }
    }

    protected void installAPK() {
        Log.i("taylor","下载1");
        File apkFile = new File("/mnt/sdcard/com.tywj.buscustomerapp/胖哒.apk");
        if (!apkFile.exists()) return;
        Log.i("taylor","下载完成");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(UpdateService.this, PACKAGE_NAME + ".fileprovider", apkFile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile),
                    "application/vnd.android.package-archive");
        }
        startActivity(intent);
//        UpdateService.this.stopSelf();
    }




        private void notifyUser(String result, int process) {
            if (builder == null) {
                return;
            }
            if (process > 0 && process < 100) {
                builder.setProgress(100, process, false);
            } else {
                builder.setProgress(0, 0, false);
            }
            if (process >= 100) {
//            builder.setContentIntent(getContentIntent());
//                getContentIntent();
            }

            builder.setContentInfo(process + "%");
            builder.setContentText(result);
            notificationManager.notify(0, builder.build());
        }

        private void getContentIntent() {
            File apkFile = new File("/mnt/sdcard/com.voga.readcool/readcool.apk");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                Uri apkUri =
                        FileProvider.getUriForFile(UpdateService.this, PACKAGE_NAME + ".fileprovider", apkFile);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile),
                        "application/vnd.android.package-archive");
            }
            startActivity(intent);
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
}
